package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.DailyTrainSeat;
import com.ruoyi.business.domain.DailyTrainStation;
import com.ruoyi.business.domain.dto.SeatCarriageDTO;
import com.ruoyi.business.domain.dto.SeatSellSegmentDTO;
import com.ruoyi.business.domain.dto.TrainSeatGroupDTO;
import com.ruoyi.business.mapper.DailyTrainSeatMapper;
import com.ruoyi.business.service.IDailyTrainSeatService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 每日座位Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class DailyTrainSeatServiceImpl implements IDailyTrainSeatService
{
    @Autowired
    private DailyTrainSeatMapper dailyTrainSeatMapper;
    @Autowired
    private DailyTrainStationServiceImpl dailyTrainStationService;

    /**
     * 查询每日座位
     * 
     * @param id 每日座位主键
     * @return 每日座位
     */
    @Override
    public DailyTrainSeat selectDailyTrainSeatById(Long id)
    {
        return dailyTrainSeatMapper.selectDailyTrainSeatById(id);
    }

    /**
     * 查询每日座位列表
     * 
     * @param dailyTrainSeat 每日座位
     * @return 每日座位
     */
    @Override
    public List<DailyTrainSeat> selectDailyTrainSeatList(DailyTrainSeat dailyTrainSeat)
    {
        return dailyTrainSeatMapper.selectDailyTrainSeatList(dailyTrainSeat);
    }

    /**
     * 新增每日座位
     * 
     * @param dailyTrainSeat 每日座位
     * @return 结果
     */
    @Override
    public int insertDailyTrainSeat(DailyTrainSeat dailyTrainSeat)
    {
        dailyTrainSeat.setCreateTime(DateUtils.getNowDate());
        return dailyTrainSeatMapper.insertDailyTrainSeat(dailyTrainSeat);
    }

    /**
     * 修改每日座位
     * 
     * @param dailyTrainSeat 每日座位
     * @return 结果
     */
    @Override
    public int updateDailyTrainSeat(DailyTrainSeat dailyTrainSeat)
    {
        dailyTrainSeat.setUpdateTime(DateUtils.getNowDate());
        return dailyTrainSeatMapper.updateDailyTrainSeat(dailyTrainSeat);
    }

    /**
     * 批量删除每日座位
     * 
     * @param ids 需要删除的每日座位主键
     * @return 结果
     */
    @Override
    public int deleteDailyTrainSeatByIds(Long[] ids)
    {
        return dailyTrainSeatMapper.deleteDailyTrainSeatByIds(ids);
    }

    /**
     * 删除每日座位信息
     * 
     * @param id 每日座位主键
     * @return 结果
     */
    @Override
    public int deleteDailyTrainSeatById(Long id)
    {
        return dailyTrainSeatMapper.deleteDailyTrainSeatById(id);
    }

    // 实现方法
    @Override
    public List<TrainSeatGroupDTO> selectDailyTrainSeatGroupByTrainAndCarriage(DailyTrainSeat dailyTrainSeat) {
        // 1. 获取所有符合条件的座位
        List<DailyTrainSeat> allSeats = dailyTrainSeatMapper.selectDailyTrainSeatList(dailyTrainSeat);

        // 2. 按车次分组
        Map<String, List<DailyTrainSeat>> trainGroups = allSeats.stream()
                .collect(Collectors.groupingBy(DailyTrainSeat::getTrainCode));

        // 3. 构建结果
        List<TrainSeatGroupDTO> result = new ArrayList<>();

        for (Map.Entry<String, List<DailyTrainSeat>> trainEntry : trainGroups.entrySet()) {
            String trainCode = trainEntry.getKey();
            List<DailyTrainSeat> trainSeats = trainEntry.getValue();

            // 4. 按车厢分组
            Map<Long, List<DailyTrainSeat>> carriageGroups = trainSeats.stream()
                    .collect(Collectors.groupingBy(DailyTrainSeat::getCarriageIndex));

            // 5. 创建车次分组DTO
            TrainSeatGroupDTO trainGroup = new TrainSeatGroupDTO();
            trainGroup.setTrainCode(trainCode);
            List<SeatCarriageDTO> carriages = new ArrayList<>();

            // 为每个车厢创建分组
            for (Map.Entry<Long, List<DailyTrainSeat>> carriageEntry : carriageGroups.entrySet()) {
                Long carriageIndex = carriageEntry.getKey();
                List<DailyTrainSeat> carriageSeats = carriageEntry.getValue();

                // 获取车厢座位类型 (从第一个座位获取)
                String seatType = carriageSeats.isEmpty() ? "未知" : carriageSeats.get(0).getSeatType();

                SeatCarriageDTO carriageDTO = new SeatCarriageDTO();
                carriageDTO.setCarriageIndex(carriageIndex);
                carriageDTO.setSeatType(seatType);
                carriageDTO.setSeats(new ArrayList<>(carriageSeats));

                carriages.add(carriageDTO);
            }

            // 按车厢序号排序
            carriages.sort(Comparator.comparing(SeatCarriageDTO::getCarriageIndex));
            trainGroup.setCarriages(carriages);

            result.add(trainGroup);
        }

        // 按车次编号排序
        result.sort(Comparator.comparing(TrainSeatGroupDTO::getTrainCode));

        return result;
    }

    /**
     * 获取座位售卖详情
     *
     * @param date 日期
     * @param trainCode 车次
     * @param seatId 座位ID
     * @return 售卖区段列表
     */
    @Override
    public List<SeatSellSegmentDTO> getSeatSellDetail(String date, String trainCode, Long seatId) {
        // 1. 获取座位信息
        DailyTrainSeat seat = dailyTrainSeatMapper.selectDailyTrainSeatById(seatId);
        if (seat == null) {
            return Collections.emptyList();
        }

        // 2. 获取列车的所有站点信息（按站序排序）
        List<DailyTrainStation> stations = dailyTrainStationService.selectByTrainCode(date, trainCode);
        if (stations.isEmpty()) {
            return Collections.emptyList();
        }

        // 3. 解析座位的sell字段
        String sell = seat.getSell();
        List<SeatSellSegmentDTO> result = new ArrayList<>();

        // 4. 如果sell是单个字符，表示全程相同状态
        if (sell.length() == 1) {
            SeatSellSegmentDTO dto = new SeatSellSegmentDTO();
            dto.setStartStation(stations.get(0).getName());
            dto.setEndStation(stations.get(stations.size() - 1).getName());
            dto.setStatus(sell);
            result.add(dto);
            return result;
        }

        // 5. 如果sell是多个字符，表示分段售卖状态
        for (int i = 0; i < sell.length(); i++) {
            // 每个字符对应一个区段
            if (i + 1 >= stations.size()) {
                break;
            }

            SeatSellSegmentDTO dto = new SeatSellSegmentDTO();
            dto.setStartStation(stations.get(i).getName());
            dto.setEndStation(stations.get(i + 1).getName());
            dto.setStatus(String.valueOf(sell.charAt(i)));
            result.add(dto);
        }

        return result;
    }


    /**
     * 按列车分页查询座位列表
     */
    @Override
    public TableDataInfo listByTrainPagination(DailyTrainSeat dailyTrainSeat, Integer pageNum, Integer pageSize) {
        // 计算分页偏移量
        int offset = (pageNum - 1) * pageSize;

        // 1. 分页查询符合条件的列车列表
        List<String> trainCodes = dailyTrainSeatMapper.selectTrainCodesWithPagination(
                dailyTrainSeat.getDate(),
                dailyTrainSeat.getTrainCode(),
                pageSize,
                offset
        );

        // 2. 获取列车总数，用于分页
        int trainTotal = dailyTrainSeatMapper.countTrainCodes(
                dailyTrainSeat.getDate(),
                dailyTrainSeat.getTrainCode()
        );

        // 3. 查询每个列车的所有座位信息
        List<TrainSeatGroupDTO> result = new ArrayList<>();
        for (String trainCode : trainCodes) {
            // 创建查询条件
            DailyTrainSeat query = new DailyTrainSeat();
            query.setDate(dailyTrainSeat.getDate());
            query.setTrainCode(trainCode);

            // 获取该车次所有座位
            List<DailyTrainSeat> trainSeats = dailyTrainSeatMapper.selectDailyTrainSeatList(query);

            // 按车厢分组
            Map<Long, List<DailyTrainSeat>> carriageGroups = trainSeats.stream()
                    .collect(Collectors.groupingBy(DailyTrainSeat::getCarriageIndex));

            // 创建车次分组DTO
            TrainSeatGroupDTO trainGroup = new TrainSeatGroupDTO();
            trainGroup.setTrainCode(trainCode);
            List<SeatCarriageDTO> carriages = new ArrayList<>();

            // 为每个车厢创建分组
            for (Map.Entry<Long, List<DailyTrainSeat>> carriageEntry : carriageGroups.entrySet()) {
                Long carriageIndex = carriageEntry.getKey();
                List<DailyTrainSeat> carriageSeats = carriageEntry.getValue();

                // 获取车厢座位类型
                String seatType = carriageSeats.isEmpty() ? "未知" : carriageSeats.get(0).getSeatType();

                SeatCarriageDTO carriageDTO = new SeatCarriageDTO();
                carriageDTO.setCarriageIndex(carriageIndex);
                carriageDTO.setSeatType(seatType);
                carriageDTO.setSeats(new ArrayList<>(carriageSeats));

                carriages.add(carriageDTO);
            }

            // 按车厢序号排序
            carriages.sort(Comparator.comparing(SeatCarriageDTO::getCarriageIndex));
            trainGroup.setCarriages(carriages);

            result.add(trainGroup);
        }

        // 4. 构建返回结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(result);
        rspData.setTotal(trainTotal); // 总列车数
        rspData.setMsg("查询成功");

        return rspData;
    }
}
